package com.team.bus.module.role.controller;

import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjframework.traceframe.common.controller.BaseController;
import org.zjframework.traceframe.common.model.DataGrid;
import org.zjframework.traceframe.common.util.JSONUtil;
import org.zjframework.traceframe.common.util.PageHelper;
import com.team.bus.module.menu.model.Menu;
import com.team.bus.module.menu.service.IMenuService;
import com.team.bus.module.role.model.Role;
import com.team.bus.module.role.pagemodel.Prole;
import com.team.bus.module.role.service.IRoleService;
import com.team.bus.module.user.model.User;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

	private IRoleService roleService;

	@Autowired
	private IMenuService menuService;

	public IRoleService getRoleService() {
		return roleService;
	}

	@Resource
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}


	private Role role = new Role();

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	@RequestMapping("/roleslist")
	public String rolelist(){

		return "/role/rolelist";
	}


	@RequestMapping("/role_datagridlist")
	public void roledatagridlist(HttpServletRequest request,HttpServletResponse response,Prole prole,PageHelper ph){
		String hql = "from Role u";
		Map<String,Object> params = new HashMap<>();
		if(prole.getText() != null){
			hql+="  where u.text like :text";
			params.put("text", "%%"+prole.getText()+"%%");
		}
		List<Role> roles = roleService.find(hql,ph.getPage(),ph.getRows(),params);
		List<Prole> proles = new ArrayList<>();
		if(roles.size()>0 && roles!=null){
			for(Role u : roles){
				Prole p = new Prole();
				BeanUtils.copyProperties(u, p);
				proles.add(p);
			}
		}
		DataGrid dg = new DataGrid();
		dg.setTotal(roleService.findHql(hql, params).size());
		dg.setRows(proles);
		super.writeJSON(dg, request, response);
	}

	/**
	 * 获取全部角色列表
	 * @return roles
	 */
	@RequestMapping(value = "/getRoleTree")
    public @ResponseBody
    List<Prole> getRoleTree() {
		Map<String,Object> param = new HashMap<>();
		String hql = "from Role";
		List<Role> roles = roleService.findHql(hql, param);
		List<Prole> proles = new ArrayList<>();
		for(Role r : roles){
			Prole pr = new Prole();
			BeanUtils.copyProperties(r, pr);
			proles.add(pr);
		}
        return proles;
    }



	@RequestMapping("/roleaddshow")
	public String roleaddshow(){
		return "/role/roleadd";
	}

	@RequestMapping("/roleadd")
	public void roleadd(HttpServletRequest request,HttpServletResponse response,Role role){

		super.writeJSON("", request, response);
	}

	/**
	/**
	 * @author 赵继
	 */
	@RequestMapping("/del")
	public void delete(HttpServletRequest request,HttpServletResponse response,String ids){
		JSONUtil json = new JSONUtil();
		String[] id = ids.split(",");
		StringBuffer hql = new StringBuffer();
		hql.append("delete Role where id in(");
		for(int i=0;i<id.length;i++){
			hql.append("'"+id[i]+"'");
			if(id.length>0 && id.length-1!=i){
				hql.append(",");
			}
		}
		hql.append(")");
		try {
			roleService.executeHql(hql.toString());
			json.setSuccess(true);
			json.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("删除失败-- 失败原因：此数据已经被引用不能被删除！");
		}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/save")
	public void save(HttpServletRequest request,HttpServletResponse response,Prole prole){
		JSONUtil json = new JSONUtil();
			try {
				if(prole!=null){
					prole.setCreatedatetime(new Date());
					BeanUtils.copyProperties(prole, role);
					Set<User> users = new HashSet<User>();
					role.setUsers(users);
					role = roleService.saveInsertRow(role);
					json.setSuccess(true);
					json.setMsg("操作成功");
					prole.setId(role.getId());
					json.setObj(prole);
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/editTo")
	public String editTo(HttpServletRequest request,HttpServletResponse response,Prole prole){

		return "/role/roleedit";
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/menuTreeTo")
	public String menuTree(HttpServletRequest request,HttpServletResponse response,String id){
		Role r = roleService.get(Role.class,id);
		request.setAttribute("role", r);
		return "/role/menuTree";
	}



	/**
	 * @author 赵继
	 */
	@RequestMapping("/edit")
	public void edit(HttpServletRequest request,HttpServletResponse response,Prole prole){

		JSONUtil json = new JSONUtil();
			try {
				if(prole!=null){
					prole.setUpdatedatetime(new Date());
					BeanUtils.copyProperties(prole, role);
					role.setMenus(new HashSet<Menu>());
					role = roleService.updateRow(role);
					json.setSuccess(true);
					json.setMsg("编辑成功");
					prole.setId(role.getId());
					json.setObj(prole);
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 * 给角色设定资源
	 */
	@RequestMapping("/grantRole")
	public void grantRole(HttpServletRequest request,HttpServletResponse response,Prole prole,String resourceIds){
        JSONUtil json = new JSONUtil();
        try {
            if(prole!=null){
                BeanUtils.copyProperties(prole, role);
                Set<Menu> menuSet = new HashSet<Menu>();
                List<Menu> mls = new ArrayList<Menu>();
                for (String menuId : resourceIds.split(",")) {
                    if (!StringUtils.isBlank(menuId)) {
                        Menu menu = menuService.get(Menu.class, menuId);
                        if (menu != null) {
                            menuSet.add(menu);
                            mls.add(menu);
                        }
                    }
                }
                role.setMenus(new HashSet<Menu>(mls));
                Role r = roleService.get(Role.class,prole.getId());
                role.setUsers(r.getUsers());
                roleService.updateRow4merge(role);
                json.setSuccess(true);
                json.setMsg("编辑成功");
                prole.setId(role.getId());
                json.setObj(prole);
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        super.writeJSON(json,request,response);
	}
}
